var app = getApp();
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var MPage = require('../MPage.js');
var Pagination = require('../../utils/pagination.js');


Page(common.extendPage(MPage, {
    data: {
        dataLoaded: false,
        page1: {
            nextPageLoading: false,
            pageLoadedAll: false,
        },
    },

    onLoad(options) {
        this._options = options;
        this._getList();
    },

    onReachBottom() {
        this.pagination && this.pagination.loadNext();
    },

    _getList() {
        var _self = this;
        var {
            goodsId
        } = this._options;

        this.pagination = new Pagination({
            url: '/openapi/CGoods/moreComment',
            params: {
                type: 1,
                goodsId: goodsId
            },
            beforeGetPage(page) {
                var page1 = _self.data.page1;

                if (page > 1) {
                    page1.nextPageLoading = true;
                    _self.setData({
                        page1
                    });
                }
            },
            getPageSuccess(page, data) {
                var page1 = _self.data.page1;
                var list = data.result.commentlist.data || [];
                var allList = _self.data.commentlist || [];
                var data = {};

                if (page == 1) {
                    data = {
                        dataLoaded: true,
                    };
                }

                if (list.length < 20) {
                    page1.pageLoadedAll = true;
                }

                page1.nextPageLoading = false;

                data.page1 = page1;
                data.commentlist = allList.concat(list);

                _self.setData(data);
            }
        });
    },

    //给评论点赞
    _likeComment(e) {
        var {
            commentId,
            isSupport
        } = e.currentTarget.dataset;

        if (isSupport == 1) {
            return;
        }
        ajax.P('/openapi/CGoods/likeComment', {
            commentId
        }, (data) => {
            var {
                commentlist
            } = this.data;

            commentlist.some((comment) => {
                if (comment.id == commentId) {
                    comment.isSupport = 1;
                    return true;
                }
            })
            this.setData({
                commentlist
            })
        });
    }
}));